package com.hu.wallpaper.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin(allowCredentials = "true", originPatterns = "*", allowedHeaders = "*")
public class IndexController {

    @Autowired
    private ResourceLoader resourceLoader;

    @Value("${server.port}")
    private String port;

    private List<String> allWallpaperNameList;

    @RequestMapping("/random-img")
    public String randomImg(HttpServletRequest request) throws IOException {
        // 读取所有的文件
        if (null == this.allWallpaperNameList || allWallpaperNameList.isEmpty()) {
            this.allWallpaperNameList = this.getAllWallpaperNameList();
        }

        int index = (int) Math.floor(Math.random() * this.allWallpaperNameList.size());

        InetAddress inetAddress = InetAddress.getLocalHost();
        String IP = inetAddress.getHostAddress();

        String contextPath = request.getContextPath();
        // 随机的图片名
        String imgName = this.allWallpaperNameList.get(index);

        // 移除本次展示的索引图片
        this.allWallpaperNameList.remove(index);

        return "http://" + IP + ":" + this.port + contextPath + "/" + imgName;
    }

    // 获取所有的壁纸名称
    private List<String> getAllWallpaperNameList() throws IOException {
//        File directory = new File(ResourceUtils.getURL("classpath:static").getPath());

        Resource resource = this.resourceLoader.getResource("classpath:static");
        File directory = resource.getFile();

        // 目录下的所有文件
        File[] files = directory.listFiles();
        if (null == files) {
            throw new RuntimeException("壁纸不存在");
        }

        List<String> allWallpaperNameList = new ArrayList<>();
        for (File file : files) {
            allWallpaperNameList.add(file.getName());
        }

        return allWallpaperNameList;
    }

}
